package com.athuiju.fenxiaoback.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.athuiju.fenxiaoback.bean.AlipayBean;
import com.athuiju.fenxiaoback.config.PropertiesConfig;
import com.athuiju.fenxiaoback.entity.OmsOrder;
import com.athuiju.fenxiaoback.entity.vo.aliReapVo;
import com.athuiju.fenxiaoback.service.ALPayService;
import com.athuiju.fenxiaoback.service.OmsOrderService;
import com.athuiju.fenxiaoback.utils.JwtUtils;
import com.athuiju.fenxiaoback.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;


@Api( description = "购物车结算支付",tags = "购物车结算支付")
@RestController
@RequestMapping("/fenxiaoback/alpaylog")
public class ALPayLogController {

    @Resource
    private ALPayService payService;//调用支付服务​

    @Autowired
    OmsOrderService orderService;


    /*阿里支付-----移动端*/
    @ApiOperation(value = "支付宝支付---移动端")
    @GetMapping("createNativeMoblie/{orderNo}")//String out_trade_no, String subject, String total_amount, String body
    public R alipayMobile(@PathVariable("orderNo")String orderNo) throws AlipayApiException {

        QueryWrapper<OmsOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderNo);
        OmsOrder order = orderService.getOne(wrapper);
        String format = new DecimalFormat("#.00").format(order.getPayAmount());//订单金额


        String out_trade_no = orderNo;       // 商户订单号，商户网站订单系统中唯一订单号，必填
        String subject = "订单名称：瞎写的"+ new Random().toString().substring(1,5);            // 订单名称，必填
        String total_amount=format;         // 付款金额，必填
        String body = "";               // 商品描述，可空
        String timeout_express="30m";   // 超时时间 可空

        //PropertiesConfig.get
        String appId = PropertiesConfig.getKey("app_id");
        String privateKey = PropertiesConfig.getKey("merchant_private_key");
        String aliPayPublicKey = PropertiesConfig.getKey("alipay_public_key");


        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",appId, privateKey, "json", "UTF-8", aliPayPublicKey, "RSA2");

        // 移动端封装请求支付信息
        String product_code="QUICK_WAP_PAY";   //销售产品码 必填
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);

        String notifyUrl = PropertiesConfig.getKey("notify_url");
        String returnUrl = PropertiesConfig.getKey("return_url");
        alipay_request.setNotifyUrl(notifyUrl);// 设置异步通知地址，支付成功后支付宝回掉通知地址
        alipay_request.setReturnUrl(returnUrl);// 设置同步地址,支付后页面跳转的地址
        // form表单生产
        String form = "";
      try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(alipay_request).getBody();
        } catch (AlipayApiException e) {

        }
        return R.ok().put("data",form);
    }





    /*阿里支付*/
    //查询是否已支付
    @ApiOperation(value = "根据订单号查询订单交易是否支付成功")
    @GetMapping("checkAlipay/{orderNo}")//String out_trade_no, String subject, String total_amount, String body
    public R checkAlipay(@PathVariable("orderNo")String orderNo,HttpServletRequest req) throws AlipayApiException, IOException {
        String memberid = JwtUtils.getMemberIdByJwtToken(req);
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do","2016102200736286","MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCmIIfWFu10s8a2m2hwfZnRvfHAiDzMnpx8HYmf0Mk6L+OPv9c6gljIlYwW5wNAvkUj6HPhJfC1uWAkL0yYHkQxBeqW1hk8wl8/b2EyS+d+Y686wxVu1nptg2hI58mLwj9Do/F/i2CwYrUy3tKzddGrOc2gX8hGYhkRR13rphiJkkdTJJJRKQTHAAW75HNf2sHcDsDfM/dIyPvPfH5/ymk3PBA1AcBh3xttMtA3f+7HDS1z7fvgGfG+QnRxb7xEfSHAdkgQkFXMCfXPTeUYLm7KvMuJ4vQ1awY0T0SiOfYZ/Om4WwZeKBGIjTX/nld2u86U2OfpU/lDfX6g22YHItnbAgMBAAECggEAI+8lcsnC01uPwDAdhzej7hqIEH1nqVslvjMlccxXup5hOtbkV2OakMjIZKvTqE1/5ySA7FKonqZahXk1uDHTzkbZV4c4LkxdDfupqpeAm3Y0kSFhoXgDQ20JQbvhfLmntZngwxYC9CRlzXslWGxDziXStL4DNDZD9djaF/71j8wawK1eYj6XcfG2RMrwUQBzowznjGjrY1qBJSk6WAOAeN6O5Z28EWA8Rw9kjbBdMoJ317RvGFh986sRpiDhoxZWbb6YAYP0zTaYWVdDLNrCf6zOTyAxwoed2COK2E5aWGGGlQYCucew9F3+ZVDaMLaJEXIr4lhP6xkwwc9n8gVaAQKBgQDjBK4ASD0SiOqPF+Jey7d/zo8M4KWt1/812QkMRDUmsVuHf4WcJqcM6xexMgd82fKcQpMg5TRpzV5p4K4UuSi2kJUgrg33A6msqSkMXt6OKNLsEObb/csxRGTTgIkYeK8K6s+mozmhFKxOZjLQ01UckpA33/fb2U2npH8e3y4BeQKBgQC7VdQ0IvsVxbhG2Sau8gdvpFC0HXa980g/Urlg371E5mZ2JDWcKDc7c3K/uWQFz6NWWr2MvFlIJ6BVYQkrzoIwK3Rortyxr+ZAxVs644jPZYmxUNln6k7sDoSudi8VkAra7a2eJRKm2CjM9Qb761V4p6SeVGh/l6y8fmFNfKoU8wKBgCW2Vk13sqWMlyKUPievQdl6b+scuokpk5zXZBhkkEvQNLtKpOBuz1tnBnWKMRI9hn8M1DInwVA+LIv8Jg8NP0UsuYlHQMyjECG9rDMA44nMIFXU7PTosUOK8BDujlfBXJq8rSgqf11R+NnBQnnMUZxAgLK3gw5DiBHsUq3HN3ZJAoGARDkWpcIThLNTz+FnOBEGaj8B8QZF5xlBN2ZuAnyY1g2+RModB/iRXMJHiNEAPymGB33WR/mT3jYoKs/C4kQ7n0VECJed4cv4Y6A8AC869KS6x2t1MWXgRhFneo2pygWCHoauUsiXiVFxUmrtlzL2FpGe3tZIlCbtjlvMHccHvccCgYAY2bbeNCN1Kx8d1RSwPsCjJrYlzbSg1BzGQN9zX4iqp7Q6HIzLTMGd+oZJnbX71s5HgM41O65JX0hd1FaBE9rUZ5mRvdAceevQ/+jd9S44nSLkGPf1z/Lk55EuY4c9Xx7gaSTBuitntYby9NGWpM8aSqa8v3qRUqfI/84rXvcyzQ==","json","utf8","MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmSVvxXiZ//6P5MAQChQiLPXwcKO8mJLTDUNd/8aeo5nqRwIcZV9M6A2AQnwruBBfM6UoSbiK4UxhnPFxN7Br6HL7NEw/zt9VNi1OGuO+TicCVNa+5J/7eivFMOW5001ZVS+nRnJ5AoVpmxOAqajcMewSGCKBh8WdoRe3aQddPslN+YnA+AuhSGk4/GyiEUrvxTVfW50FQXHxHbEU2jCdxtPf6AEuC/I/6w1R63uWTgYv3FLvpYSsRX5ze8adh4IiHfDAiEOgJIzQTAdSLiV/BLufosox2NKqHn82l8DmhRg4NGI2SvwJN5Ku9RVuOwNkE6NYS3H7oTy6bVBZbufNHQIDAQAB","RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        //"\"trade_no\":\"2014112611001004680073956707\"," +
        //"\"org_pid\":\"2088101117952222\"" +
        request.setBizContent("{" +
                "\"out_trade_no\":\""+orderNo+"\"" +"}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);

        //boolean isSucc=false;
        //for (Object key : alRespObjMap.keySet()) {
        //    System.out.println(key+"---"+alRespObjMap.get(key));
        //}
        if(response.isSuccess()){
            Map maps = (Map)JSON.parse(response.getBody());
            Object alRespObj = maps.get("alipay_trade_query_response");

            Map alRespObjMap = (Map)JSON.parse(alRespObj.toString());
            String trade_status = alRespObjMap.get("trade_status").toString();
            //WAIT_BUYER_PAY  TRADE_CLOSED  TRADE_SUCCESS   TRADE_FINISHED
            if (!StringUtils.isEmpty(trade_status)){
                if(trade_status.equalsIgnoreCase("WAIT_BUYER_PAY")){
                    return R.error().put("msg","交易创建，等待买家付款");
                }
                if(trade_status.equalsIgnoreCase("TRADE_CLOSED")){
                    return R.error().put("msg","未付款交易超时关闭，或支付完成后全额退款");
                }
                if(trade_status.equalsIgnoreCase("TRADE_SUCCESS")){
                    //    用户付款成功，修改订单状态（status）为待发货  1
                    QueryWrapper<OmsOrder> orderWrapper=new QueryWrapper<>();
                    orderWrapper.eq("order_sn",orderNo);
                    orderWrapper.eq("member_id",memberid);

                    OmsOrder order = orderService.getOne(orderWrapper);

                    order.setStatus(1);
                    order.setPaymentTime(new Date());


                    orderService.update(order,orderWrapper);

                    return R.ok().put("msg","交易支付成功").put("code",200).put("note","交易支付成功，订单状态'status'值会变为1(待发货)，’我的订单‘页面显示 ‘立即付款’按钮改为‘确认收货’按钮\n如果用户支付失败，按钮为'立即付款'");

                }
                if(trade_status.equalsIgnoreCase("TRADE_FINISHED")){
                    return R.error().put("msg","交易结束，不可退款");
                }
            }

        } else {System.out.println("调用失败");}
            return R.error().put("msg","未找到此订单的支付信息。");
        }



    @ApiOperation(value = "修改订单为已支付---无需真正支付")
    @GetMapping("updatePaid/{orderNo}")//String out_trade_no, String subject, String total_amount, String body
    public R updatePaid(@PathVariable("orderNo")String orderNo,HttpServletRequest req){
        String memberid = JwtUtils.getMemberIdByJwtToken(req);
        QueryWrapper<OmsOrder> orderWrapper=new QueryWrapper<>();
        orderWrapper.eq("order_sn",orderNo);
        orderWrapper.eq("member_id",memberid);

        OmsOrder order = orderService.getOne(orderWrapper);

        order.setStatus(1);
        order.setPaymentTime(new Date());

        orderService.update(order,orderWrapper);
        return  R.ok().put("msg","订单修改已支付成功,status值改变为1，订单状态变为 ’待发货‘");
    }




}
